package com.cooca.carborganizer.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.cooca.carborganizer.client.DBConnection;
import com.cooca.carborganizer.client.objects.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class MySQLConnection extends RemoteServiceServlet implements
		DBConnection {

	private static final long serialVersionUID = -701043759750496571L;
	private Connection conn = null;
	private String url = "jdbc:mysql://127.0.0.1/carborganizer";
	private String user = "guest";
	private String pass = "test";
	
	private String ConnectionError = null;
	private String CommunicationError = null;
	

	public MySQLConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, pass);
		} catch (Exception e) {
			e.printStackTrace();
			ConnectionError = e.getMessage();
		}
	};

	public User authenticateUser(String user, String pass) {

		User ReturnUser = null;
		String StatementString = "select * from users where username = \""
				+ user + "\" AND " + "password = \"" + pass + "\"";
		System.out.println("Statement : " + StatementString);
		try {
			PreparedStatement ps = conn
					.prepareStatement(StatementString);
			ResultSet result = ps.executeQuery();
			while (result.next()) {
				ReturnUser = new User(result.getString(1), result.getString(2));
			}
			result.close();
			ps.close();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
			CommunicationError = sqle.getMessage();
		}
		if (ReturnUser == null) ReturnUser = new User(ConnectionError, CommunicationError);
		
		return ReturnUser;
	}

}
